﻿using Barkod.Utility;
using Barkod.Utility.Grid;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraReports.UI;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;

namespace Barkod
{
    public partial class BarkodOkutma : XForm
    {
        public int BarkodSayId = 0;


        public BarkodOkutma()
        {
            InitializeComponent();
        }

        public DataTable SourceData = null;
        Oturum oturum = null;
        SpreadsheetGear.IWorkbook workbook = null;

        private void BarkodOkutma_Load(object sender, EventArgs e)
        {
            using (oturum = new Oturum())
            {
                if (oturum.ShowDialog() == DialogResult.OK)
                {
                    BarkodSayId = oturum.BarkodSayId;

                    GridMenu gm = GridManager.GetManager(gv).GridMenu;
                    gm.AddMenu("Seçili satırların koli barkodlarını yazdır", KoliBarkod);
                    gm.AddMenu("Seçili satırların model barkodlarını yazdır", ModelBarkod);
                    Bind();

                    this.KeyPreview = true;
                    this.KeyPress += BarkodOkutma_KeyPress;
                    timer.Interval = 1 * 1000;
                    gv.Focus();
                    SonBarkod.Text = "";
                }
                else
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
            }
        }

        private void Bind()
        {
            workbook = SpreadsheetGear.Factory.GetWorkbook(oturum.FileName);
            System.Data.DataSet dataSet = workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.FormattedText);

            SourceData = dataSet.Tables[0];

            SourceData.Columns.Add("ToplamAdet", typeof(int));
            foreach (DataRow dr in SourceData.Rows)
                dr["ToplamAdet"] = dr["Adet"].ToIntNN();

            SourceData.Columns.Remove("Adet");
            SourceData.Columns["ToplamAdet"].ColumnName = "Adet";
            SourceData.Columns["Adet"].Caption = "Adet";

            DataTable dtToplam = AppSession.DataManager.ExecuteDataTable("GetBarkodSayToplam", BarkodSayId);
            foreach (DataRow dr in dtToplam.Rows)
            {
                DataRow[] drToplams = SourceData.Select(string.Format("[Barkod] = '{0}' and [KoliNo] = '{1}'", dr["KoliNo"].ToStringNN(), dr["Barkod"].ToStringNN()));
                if (drToplams.Length == 1)
                    drToplams[0]["Adet"] = dr["Toplam"].ToIntNN();
                else
                {
                    //TODO: ??? Uyarı mı verelim?
                }
            }



            gv.Init(SourceData);


            BindingSource bs = new BindingSource(SourceData.DataSet, SourceData.TableName);
            pivot.DataSource = bs;

            pivot.Fields.Clear();

            foreach (DataColumn dc in SourceData.Columns)
            {
                if (dc.ColumnName == "Adet")
                {
                    PivotGridField fd = new PivotGridField("Adet", PivotArea.DataArea);

                    fd.FieldName = fd.Caption = "Adet";
                    fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    fd.CellFormat.FormatString = "#,###.##";
                    //   fd.SetAreaPosition(PivotArea.DataArea, 0);
                    fd.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;
                    pivot.Fields.Add(fd);
                }
                else if (dc.ColumnName == "KoliNo")
                {
                    PivotGridField fd = new PivotGridField(dc.ColumnName, PivotArea.ColumnArea);
                    pivot.Fields.Add(fd);
                }
                else if (dc.ColumnName == "Barkod")
                {
                    PivotGridField fd = new PivotGridField(dc.ColumnName, PivotArea.RowArea);
                    pivot.Fields.Add(fd);
                }
                else
                {
                    PivotGridField fd = new PivotGridField(dc.ColumnName, PivotArea.FilterArea);
                    pivot.Fields.Add(fd);
                }
            }

            //string[] colNames = new string[] { "Toplam Miktar", "Malzeme", "EAN/UPC kodu", "Ana beden", "Kısa metin", "Müşteri", "Ad 1", "Onaylı Miktar" };
            //foreach (DataColumn dc in SourceData.Columns)
            //{
            //    if (!colNames.Contains(dc.ColumnName))
            //        gv.MakeColumnInvisible(dc.ColumnName);
            //}


            gv.AddSummary();
            gv.MakeReadOnly();
            gv.BestFitColumns();
        }

        private void ModelBarkod(object sender, EventArgs e)
        {
            DataTable dtKoli = new DataTable();
            dtKoli.Columns.Add("Barkod", typeof(Int64));
            List<string> ids = new List<string>();

            foreach (int i in gv.GetSelectedRows())
            {

                string id = gv.GetRowCellValue(i, "Barkod").ToStringNN();
                if (!ids.Contains(id))
                {
                    ids.Add(id);
                    dtKoli.Rows.Add(UInt64.Parse(id));
                }
            }

            if (dtKoli.Rows.Count > 0)
            {
                KoliEtiketi ke = new KoliEtiketi(dtKoli, 2);
                ke.ShowPreview();
            }
        }

        private void KoliBarkod(object sender, EventArgs e)
        {
            DataTable dtKoli = new DataTable();
            dtKoli.Columns.Add("Barkod", typeof(Int64));
            List<string> ids = new List<string>();

            foreach (int i in gv.GetSelectedRows())
            {

                string id = gv.GetRowCellValue(i, "KoliNo").ToStringNN();
                if (!ids.Contains(id))
                {
                    ids.Add(id);
                    dtKoli.Rows.Add(UInt64.Parse(id));
                }
            }

            if (dtKoli.Rows.Count > 0)
            {
                KoliEtiketi ke = new KoliEtiketi(dtKoli, 1);
                ke.ShowPreview();
            }

            SonBarkod.Text = "";
        }


        void BarkodOkutma_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool isDigit = Char.IsDigit(e.KeyChar);
            //if (isDigit)
            {
                timer.Enabled = true;
                SonBarkod.Text += e.KeyChar.ToString();
            }
        }

        private void BarkodOkundu(string Barkod)
        {
            if (seKoliNo.Value.ToIntNN() > 0)
            {
                AppSession.DataManager.ExecuteNonQuery("UpdBarkodSayLines", Barkod, BarkodSayId, seKoliNo.Value.ToIntNN());

                DataRow[] drs = SourceData.Select("[KoliNo] = '" + seKoliNo.Value.ToString() + "' and [Barkod] = '" + Barkod + "'");
                if (drs.Length == 1)
                    drs[0]["Adet"] = drs[0]["Adet"].ToIntZero() + 1;
                else
                {
                    //TODO ??? Uyarı verelim mi?
                }
                gv.LocateByValue("[Barkod]", Barkod);

                pivot.RefreshData();
                //gv.BestFitColumns();
            }
            else
            {

            }
        }

        private void btnSil_Click(object sender, EventArgs e)
        {
            AppSession.DataManager.ExecuteNonQuery("DelBarkodSayLines", BarkodSayId, seKoliNo.Value.ToIntNN());
            Bind();
        }


        private void timer_Tick(object sender, EventArgs e)
        {
            Int64 val = 0;
            if (Int64.TryParse(SonBarkod.Text, out val))
            {
                string realCode = val.ToString();
                //realCode = realCode.Substring(seIlk.Value.ToIntNN() , realCode.Length - seSon.Value.ToIntNN() - seIlk.Value.ToIntNN() );

                if (realCode.Length - seSon.Value.ToIntNN() == seKoli.Value.ToIntNN())
                {
                    realCode = realCode.Substring(0, realCode.Length - seSon.Value.ToIntNN());
                    seKoliNo.Value = realCode.ToIntNN();
                }
                else if (realCode.Length - seIlk.Value.ToIntNN() == seModel.Value.ToIntNN())
                {
                    realCode = realCode.Substring(seIlk.Value.ToIntNN(), realCode.Length - seIlk.Value.ToIntNN());
                    BarkodOkundu(realCode);
                }

            }
            SonBarkod.Text = "";
            timer.Enabled = false;
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sd = new SaveFileDialog())
            {

                sd.DefaultExt = "xlsx";
                sd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string fileName = oturum.FileName.Replace(".xlsx", "_" + BarkodSayId + ".xlsx");
                sd.FileName = fileName;
                sd.ShowDialog();
                fileName = sd.FileName;

                //pivot.ExportToXlsx(sd.FileName);

                SpreadsheetGear.IRange range = workbook.Worksheets[0].Cells["A1"];
                workbook.Worksheets[0].Cells[0, 3].EntireColumn.NumberFormat = "@";
                range.CopyFromDataTable(SourceData, SpreadsheetGear.Data.SetDataFlags.None);

                workbook.SaveAs(fileName, SpreadsheetGear.FileFormat.OpenXMLWorkbook);

                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = sd.FileName;
                info.UseShellExecute = true;    //?
                info.ErrorDialog = true;
                Process process = Process.Start(info);
            }
        }
    }
}
